
#include "Area.h"

Area::Area(){
	tilesetSurface = NULL;
	tiles = NULL;
}

bool Area::loadArea(char* areaFile){
	
	std::ifstream file(areaFile);

	char tilesetName[65];
	char realTilesetName[80];

	if(file.fail() || !file.good())
		return false;

	while( file.peek() == ';' || file.peek() == '\n' )
		file.ignore(256,'\n');
	
	file >> std::skipws >> areaWidth;

	while( file.peek() == ';' || file.peek() == '\n' )
		file.ignore(256,'\n');

	file >> std::skipws >> areaHeight;

	if( areaWidth <= 0 || areaHeight <= 0 )
		return false;

	if(!initTiles())
		return false;

	while( file.peek() == ';' || file.peek() == '\n' )
		file.ignore(256,'\n');

	file >> std::skipws >> tilesetName;
	sprintf(realTilesetName, "tilesets\\%s\\%s",tilesetName,tilesetName);

	if(!tileset.loadTilesetDef(realTilesetName))
		return false;

	sprintf(realTilesetName, "tilesets\\%s\\%s.png", tilesetName, tilesetName);

	if((tilesetSurface = Surface::OnLoad(realTilesetName)) == NULL)
		return false;

	while( file.peek() == ';' || file.peek() == '\n' )
		file.ignore(256,'\n');

	int c;
	for( int i=0; i< areaHeight; i++ )
		for( int j=0; j< areaWidth; j++ )
		{
			if(!tiles[i][j].init(&tileset, tilesetSurface))
				return false;
			file >> std::skipws >> c;
			tiles[i][j].setType(c);
		}

	file.close();

	return true;
}

bool Area::initTiles(){

	if(tiles != NULL)
		return false;

	tiles = new Tile*[areaHeight];

	if(tiles == NULL)
		return false;

	for(int i=0; i< areaHeight; i++)
		tiles[i] = new Tile[areaWidth];

	return true;
}

void Area::loop(){
	for(int i=0; i<areaHeight; i++)
		for(int j=0; j<areaWidth; j++)
			tiles[i][j].loop();
}

void Area::render(SDL_Surface* destSurface, int initX, int initY){

	int c, l;

	c = 32;
	l = 24;

	if(initX + c >= areaWidth)
		c = areaWidth - initX;

	if(initY + l >= areaHeight)
		l = areaHeight - initY;

	for(int i=0; i<l; i++)
		for(int j=0; j<c; j++)
			tiles[initY+i][initX+j].render(destSurface, j*25, i*25);
}

void Area::cleanup(){
	
	for(int i=0; i< areaHeight; i++)
		delete[] tiles[i];

	delete[] tiles;
	tiles = NULL;

	areaObjects.clear();

	tileset.cleanup();

	if(tilesetSurface != NULL)
		SDL_FreeSurface(tilesetSurface);
}

bool Area::saveArea(char* fileName){

	std::ofstream newFile(fileName);

	if( newFile.fail() || !newFile.good() )
		return false;



	newFile.close();
	
	return true;
}
